package com.example.demo.service.impl;


import com.example.demo.domain.*;
import com.example.demo.repository.ShareMapper;
import com.example.demo.repository.ShareUserMapper;
import com.example.demo.service.ShareService;
import com.example.demo.viewmodel.admin.message.MessagePageRequestVM;
import com.example.demo.viewmodel.client.user.MessageRequestVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class ShareServiceImpl  implements ShareService {

    private final ShareMapper shareMapper;
    private final ShareUserMapper shareUserMapper;

    @Autowired
    public ShareServiceImpl(ShareMapper shareMapper, ShareUserMapper shareUserMapper) {
        this.shareMapper = shareMapper;
        this.shareUserMapper = shareUserMapper;
    }

    @Override
    public List<Message> selectMessageByIds(List<Integer> ids) {
        return shareMapper.selectByIds(ids);
    }

    @Override
    public PageInfo<MessageUser> studentPage(MessageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                shareUserMapper.studentPage(requestVM)
        );
    }

    @Override
    public PageInfo<Message> page(MessagePageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                shareMapper.page(requestVM)
        );
    }

    @Override
    public List<MessageUser> selectByMessageIds(List<Integer> ids) {
        return shareUserMapper.selectByMessageIds(ids);
    }

    @Override
    @Transactional
    public void sendMessage(Message message, List<MessageUser> messageUsers) {
        shareMapper.insertSelective(message);
        messageUsers.forEach(d -> d.setMessageId(message.getId()));
        shareUserMapper.inserts(messageUsers);
    }

    @Override
    @Transactional
    public void read(Integer id) {
        MessageUser messageUser = shareUserMapper.selectByPrimaryKey(id);
        if (messageUser.getReaded())
            return;
        messageUser.setReaded(true);
        messageUser.setReadTime(new Date());
        shareUserMapper.updateByPrimaryKeySelective(messageUser);
        shareMapper.readAdd(messageUser.getMessageId());
    }

    @Override
    public Integer unReadCount(Integer userId) {
        return shareUserMapper.unReadCount(userId);
    }

    @Override
    public Message messageDetail(Integer id) {
        MessageUser messageUser = shareUserMapper.selectByPrimaryKey(id);
        return shareMapper.selectByPrimaryKey(messageUser.getMessageId());
    }

}
